import {
  SaveKnowledgeType,
  GetKnowledgeTypeList,
  UpdateKnowledgeType,
  DeleteKnowledgeType,
  getNodeInfoByTypeApi,
  getDicList
} from '@/api/knowledgeTypeAdd/index.js'
export default {
  data() {
    return {
      loading: false,
      isExpandAll: true,
      dialogVisible: false,
      queryParam: {
        typeName: undefined
      },
      addform: {
        typeName: undefined,
        parentId: undefined,
        sort: 1,
        color: '#409EFF',
        nodeFieldJson: []
      },
      // 表格树数据
      TreeList: [],
      tableList: [],
      inputMethodOption: [
        {
          value: '1',
          label: '输入框'
        },
        {
          value: '2',
          label: '下拉框'
        }
      ],
      Isflag: false,
      InputMethodIncludes: []
    }
  },
  mounted() {
    this.handleGetKnowledgeTypeList()
    this.getDicList()
  },
  methods: {
    // 重置搜索表单
    handleReset() {
      this.queryParam = {
        typeName: undefined,
        status: undefined,
        description: undefined
      }
      this.handleGetKnowledgeTypeList()
    },
    /** 获取匹配输入方式下拉框的字典 */
    getDicList() {
      getDicList().then(res => {
        if (res.data.code !== 200) {
          this.$message.error(res.data.message)
          return
        }
        const data = res.data.data
        const entries = Object.entries(data)

        entries.forEach(([key]) => {
          this.InputMethodIncludes.push(key)
        })
      })
    },
    handleInputChange(value, row) {
      if (this.InputMethodIncludes.includes(value)) {
        row.inputMethod = '2'
      } else {
        row.inputMethod = '1'
      }
    },
    handleOpenModal(value, type) {
      if (type === 'edit') {
        this.tableList = []
        const data = {
          nodeType: value.id
        }
        const copyInfo = JSON.parse(JSON.stringify(value)) // 深拷贝一下，避免发生修改弹窗内容，导致页面内容被修改
        getNodeInfoByTypeApi(data).then(res => {
          if (res.data.code === 200 && res.data.data == null) {
            // 编辑
            this.addform = copyInfo
            // 用于回显表格数据
            if (value.nodeFieldJson !== null) {
              const toParse = JSON.parse(value.nodeFieldJson)
              this.tableList = toParse
              this.addform.nodeFieldJson = toParse // 在转回来是因为确定方法都会走stringify，避免再做处理
            }

            this.Isflag = true
            this.dialogVisible = true
          } else {
            return this.$message.warning('已经创建过节点的类型不可编辑！')
          }
        })
      } else {
        this.addform.id = undefined
        if (this.addform.parentId !== 0) {
          this.addform.parentId = value.id
        }
        this.addform.typeName = undefined
        this.addform.sort = 1
        this.addform.color = '#409EFF'
        this.addform.nodeFieldJson = []
        this.tableList.length = 0
        this.Isflag = false
        this.dialogVisible = true
      }
    },
    handleCloseModal(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
    },
    handleSearch() {
      this.handleGetKnowledgeTypeList()
    },

    /** 添加知识类型 */
    handleAddKnowledgeType() {
      this.tableList = []
      this.addform = {
        typeName: undefined,
        sort: 1,
        color: '#409EFF'
      }
      // 将父知识类型ID设置为0，表示这是一个顶级知识类型
      this.addform.parentId = 0
      this.dialogVisible = true
      // 根据Isflag的值来决定是新增
      this.Isflag = false
    },

    /** 获取知识类型树列表 */
    handleGetKnowledgeTypeList() {
      this.loading = true
      GetKnowledgeTypeList(this.queryParam).then(res => {
        this.TreeList = res.data.data
        this.loading = false
      })
    },

    /** 保存知识类型 */
    handleSaveKnowledgeType(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false
        let flag = false
        this.tableList.forEach(item => {
          if (!item.name || item.inputMethod === '') {
            flag = true
            this.$message.warning('请输入节点名称')
            return false
          }
        })
        if (flag) {
          return false
        }
        this.addform.nodeFieldJson =
          this.tableList.length > 0
            ? JSON.stringify(this.tableList)
            : JSON.stringify([])
        if (this.Isflag) {
          /** 调用更新知识类型接口 */
          UpdateKnowledgeType(this.addform).then(res => {
            if (res.data.code !== 200) {
              this.$message.error(res.data.message)
              return
            }
            this.$message.success(res.data.message)
            this.handleGetKnowledgeTypeList()
          })
        } else {
          SaveKnowledgeType(this.addform).then(res => {
            if (res.data.code !== 200) {
              this.$message.error(res.data.message)
              return
            }
            this.$message.success(res.data.message)
            this.handleGetKnowledgeTypeList()
          })
        }
        this.$refs[formName].resetFields()
        this.addform = {
          typeName: undefined,
          parentId: undefined,
          sort: 1,
          color: '#409EFF',
          nodeFieldJson: []
        } // 以防有的值没有被置空，从而导致不应该发生的问题
        this.dialogVisible = false
      })
    },

    /** 删除知识类型 */
    async handleDeleteKnowledgeType(row) {
      if (!row.id) {
        this.$message.warning('请选择要删除的知识类型')
        return
      }

      const params = {
        nodeType: row.id
      }

      const { data } = await getNodeInfoByTypeApi(params)

      if (data.code === 200 && data.data !== null) {
        this.$message.warning('已经创建过节点的类型不可删除')
        return
      }

      this.$confirm('是否删除该知识类型', '提示', { type: 'warning' }).then(
        () => {
          DeleteKnowledgeType({ id: row.id }).then(res => {
            if (res.data.code !== 200) {
              this.$message.error(res.data.message)
              return
            }
            this.$message.success(res.data.message)
            this.handleGetKnowledgeTypeList()
          })
        }
      )
    },

    /** 添加单个 */
    handleAdd() {
      this.tableList.push({
        name: '',
        inputMethod: ''
      })
    },
    /** 删除表格中的单个 */
    handleDelete(no, row) {
      this.tableList.splice(no, 1)
    }
  }
}
